//
//  WYMMainTabBar.swift
//  iOS11weibo
//
//  Created by 王应明 on 16/7/19.
//  Copyright © 2016年 DescendantsOftheSun. All rights reserved.
//

import UIKit

class WYMMainTabBar: UITabBar {
    
    var composeCallback: (() -> Void)?

    //懒加载按钮
    lazy var composeButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.Custom)
        
        //设置按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //添加到tabbar
        self.addSubview(button)
        
        button.addTarget(self, action: #selector(WYMMainTabBar.composeClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    //按钮数量
    
    let itemCount: Int = 5
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //计算每个按钮的宽度
        let newItemWidth = self.frame.size.width/CGFloat(itemCount)
        var index = 0
        //遍历所有item
        for item in self.subviews {
            let cls = NSClassFromString("UITabBarButton")!
            if item.isKindOfClass(cls) {
                //重新设置item的frame
                item.frame = CGRect(x: CGFloat(index) * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
                index += 1
                if index == 2 {
                    index += 1
                }
            }
        }
        composeButton.frame = CGRectMake(2 * newItemWidth, 0, newItemWidth, self.frame.height)
    }
    
    //点击事件
    func composeClick() {
        
        composeCallback?()
    }
    
}
